﻿/// <reference path="/Scripts/jquery.min.js" />

/*
 * 四级联动
 * 提供参数 change
 * change：回调 带一个 json对象 all全部 last最后选中的
 * level:设置允许选中到第几级，最低 1级 最高 4级 默认全部
 * split:分隔符 用于分割多级文本使用 包括 codel 默认 /
 * 它会绑定对应的元素4个attribute属性值
 *  1、data-area-code 选中的全部编号
 *  2、data-area-name 选中的全部区域名称
 *  3、data-area-lastcode 选中的最后一个编号
 *  4、data-area-lastname 选中的最后一个区域名称
 *  注意: 依赖 areajson.js 文件数据集
*/

$.fn.areaPick = function (opts) {
    if (opts === undefined) { opts = {}; }

    var $this = this;
    //默认选择所有层级
    if (!opts.hasOwnProperty("level"))
        opts.level = 0;

    //分隔符
    if (!opts.hasOwnProperty("split")) {
        opts.split = " / ";
    }

    //加载对应位置
    var css = { top: 0, left: 0, height: 0 };

    //css
    css.top = this.offset().top + this.outerHeight();
    css.left = this.offset().left;
    var areaBodyCss = "top:" + css.top + "px;";
    areaBodyCss += "left:" + css.left + "px;";
    areaBodyCss += "width:" + this.outerWidth() + "px";

    //骨架
    var areaHtml = {
        tab: {
            province: '<div class="active" data-area="province">省份</div>',
            city: '<div data-area="city">城市</div>',
            district: '<div data-area="district">县区</div>',
            street: '<div data-area="street">街道</div>'
        },
        html: {
            province: '<div class="area-select area-province">' +
            '    <ul data-area="province"></ul>' +
            '</div>',
            city: '<div class="area-select area-city">' +
            '   <ul data-area="city"></ul>' +
            '</div>',
            district: '<div class="area-select area-district">' +
            '   <ul data-area="district"></ul>' +
            '</div>',
            street: '<div class="area-select area-street">' +
            '   <ul data-area="street"></ul>' +
            '</div>',
        }
    };

    if (opts.level == 1) {
        areaHtml.tab.city = "";
        areaHtml.tab.district = "";
        areaHtml.tab.street = "";
        areaHtml.html.city = "";
        areaHtml.html.district = "";
        areaHtml.html.street = "";
    } else if (opts.level == 2) {
        areaHtml.tab.district = "";
        areaHtml.tab.street = "";
        areaHtml.html.district = "";
        areaHtml.html.street = "";
    } else if (opts.level == 3) {
        areaHtml.tab.street = "";
        areaHtml.html.street = "";
    }

    var _areaTabHtmlContent = (
        areaHtml.tab.province +
        areaHtml.tab.city +
        areaHtml.tab.district +
        areaHtml.tab.street
    );
    var _areaHtmlContent = (
        areaHtml.html.province +
        areaHtml.html.city +
        areaHtml.html.district +
        areaHtml.html.street
    );

    //初始化骨架
    function _initHtml() {
        if ($(".area-select-body").length > 0) { return; }
        var html = '<div class="area-select-body" style="' + areaBodyCss + '" >' +
            '        <div class="area-select-tab">' + _areaTabHtmlContent + ' ' +
            '        </div>' +
            '<div class="area-select-title">' +
            '            <span data-title="province"></span>' +
            '            <span data-title="city"></span>' +
            '            <span data-title="district"></span>' +
            '            <span data-title="street"></span>' +
            '        </div>' +
            '        <div class="area-select-content">' + _areaHtmlContent + '' +
            '        </div>' +
            '<div class="area-select-btn">' +
            '<span title="关闭">x</span>' +
            '</div>' +
            '    </div>';
        $(document.body).append(html);
        $(".area-select-body").fadeIn(300);
        //判断位置
        if ($(window).outerHeight() < $this.offset().top + 308) {
            $(".area-select-body").css({ "top": $this.offset().top - 308 });
        }
    }
    _initHtml();
    //绑定关闭事件
    $(".area-select-body>div.area-select-btn > span").click(function () {
        _Close();
    });


    //初始化数据
    function _init(code, type) {
        var html = '';
        if (code === undefined && type === undefined) {
            type = "province";
            $.each($_address, function (k, v) {
                if (v.p == 0) {
                    html += '<li data-code="' + v.c + '">' + v.n + '</li>';
                }
            });
        } else {
            var iskey = false;
            $.each($_address, function (k, v) {
                if (v.p == code) {
                    html += '<li  data-code="' + v.c + '">' + v.n + '</li>';
                    iskey = true;
                }
            });
            if (!iskey) { _Close(); return; }
        }
        $(".area-select > ul[data-area='" + type + "']").html(html);
    }


    //打开内容样式
    function openAreaSelectContent(t) {

        $(".area-select-tab > div").removeClass("active");
        $(".area-select-tab > div[data-area='" + t + "']").addClass("active");

        //打开当前的选项

        $(".area-select").hide();
        $(".area-select-content > div.area-" + t + "").show();
    }

    //清空数据
    function selectTitleEmpty(t) {
        if (t == "province") {
            $(".area-select-title>span[data-title!='province']").text("")
                .removeAttr("data-code");
            return;
        }

        if (t == "city") {
            $(".area-select-title>span[data-title='district']").text("")
                .removeAttr("data-code");
            $(".area-select-title>span[data-title='street']").text("")
                .removeAttr("data-code");
            return;
        }

        if (t == "district") {
            $(".area-select-title>span[data-title='street']").text("")
                .removeAttr("data-code");
            return;
        }
    }

    //获取选中的数据
    function _GetSelectVlaue() {
        var _code = [], _name = [];
        $(".area-select-title>span[data-title]").each(function (i, dom) {
            var a = $(dom).attr("data-code");
            var v = $(dom).text();
            if ((a !== undefined) && (a != "")) {
                _code[i] = $(dom).attr("data-code");
                _name[i] = $(dom).text();
            }
        });

        return { code: _code, name: _name };
    }


    //关闭
    function _Close() {
        $(".area-select-body").fadeOut(300, function () {
            $(this).remove();
        });

    }

    //省展开
    $(".area-select-tab>div").click(function () {
        $(this).siblings().removeClass("active");
        $(this).addClass("active");
        $(".area-select").hide();
        $(".area-" + $(this).attr("data-area")).show();
    })

    //选择
    var _DwellAddress = { province: "", city: "", district: "", street: "" };
    $(".area-select").on("click", ">ul>li", function () {
        var parent_arr = $(this).parent("ul").attr("data-area");
        var this_code = $(this).attr("data-code");
        var this_text = $(this).text();
        _DwellAddress[parent_arr] = this_text;
        var change_arr = parent_arr;
        switch (change_arr) {
            case "province":
                change_arr = "city";
                break;
            case "city":
                change_arr = "district";
                break;
            case "district":
                change_arr = "street";
                _DwellAddress[parent_arr] = this_text;
                break;
        }

        //清空选中数据
        selectTitleEmpty(parent_arr);

        $(".area-select-title>span[data-title='" + parent_arr + "']")
            .text(this_text).attr("data-code", this_code);

        $(this).siblings().removeClass("active");
        $(this).addClass("active");

        //属性
        $($this).attr({ "data-area-code": "", "data-area-name": "", "data-area-value": JSON.stringify(_DwellAddress) });
        var code = _GetSelectVlaue().code;
        var name = _GetSelectVlaue().name;
        $($this).attr({
            "data-area-code": code.join(opts.split), "data-area-name": name.join(opts.split),
            "data-area-lastcode": this_code, "data-area-lastname": this_text
        });

        $($this).val(name.join(opts.split));
        //回调
        var changeOpts = {
            all: {
                code: code.join(opts.split),
                name: name.join(opts.split),
                json: _DwellAddress
            },
            last: {
                code: this_code,
                name: this_text
            }
        };
        if (opts.hasOwnProperty("change")) {
            opts.change(changeOpts);
        }


        //填充下一页数据
        _init(this_code, change_arr);

        //关闭
        if (parent_arr == "province" && opts.level == 1) {
            _Close(); return;
        }
        if (parent_arr == "city" && opts.level == 2) {
            _Close(); return;
        }
        if (parent_arr == "district" && opts.level == 3) {
            _Close(); return;
        }
        if (parent_arr == "street") { _Close(); return; }
        //打开下一页
        openAreaSelectContent(change_arr);
    })

    _init();
}
/*
* 获取值 返回JSON
*/
$.fn.areaPickGet = function () {
    var _json = this.attr("data-area-value");
    if (_json === undefined || _json == null || _json == "") { return { province: "", city: "", district: "", street: "" }; }
    return JSON.parse(_json);
}


/*
 * 依赖 areajson.js 文件数据集
 * 它跟 areaPick 使用同一个js数据库
 * split：分隔符 用于分割多级文本使用 包括 codel 默认 /
 * lastcode：最后一个选中的 code 它会反向递归出对应的所有数据
 * text：直接赋值于该元素，不在查询
 * 用于反向查询数据 初始化
*/
$.fn.areaPickInit = function (opts) {
    if (opts === undefined) { opts = {}; }

    if (!opts.hasOwnProperty("lastcode")) {
        opts.lastcode = 0;
    }
    //分隔符
    if (!opts.hasOwnProperty("split")) {
        opts.split = " / ";
    }

    //如果设置纯文本
    if (!opts.hasOwnProperty("text")) {
        opts.text = "";
    }

    if (opts.text != "") {
        this.val(opts.text);
        return;
    }

    //递归获取对应信息
    var _areaName = [];
    function _GetName(p) {
        if (p == 0) { return; }
        $.each($_address, function (k, v) {
            if (v.c == p) {
                _GetName(v.p);
                _areaName.push(v.n);
                return false;
            }
        })
    }
    //初始化数据
    _GetName(opts.lastcode);
    this.val(_areaName.join(opts.split));

}